<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>送货单管理系统</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: "Microsoft YaHei", sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            padding: 20px;
            color: #333;
        }
        
        .login-container {
            max-width: 400px;
            margin: 100px auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        
        .login-container h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }
        
        .login-form .form-group {
            margin-bottom: 20px;
        }
        
        .login-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .login-form input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        
        .login-btn {
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        
        .login-btn:hover {
            background-color: #2980b9;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: none; /* 初始隐藏，登录后显示 */
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-section, .preview-section, .history-section, .user-management-section {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        
        h2 {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #3498db;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .product-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .product-table th, .product-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .product-table th {
            background-color: #f2f2f2;
        }
        
        .product-table input {
            width: 95%;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        
        .btn-success {
            background-color: #2ecc71;
            color: white;
        }
        
        .btn-danger {
            background-color: #e74c3c;
            color: white;
        }
        
        .btn-warning {
            background-color: #f39c12;
            color: white;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .preview-container {
            border: 1px solid #ddd;
            padding: 20px;
            background-color: white;
            overflow-y: auto;
        }
        
        .delivery-note {
            width: 100%;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .company-header {
            text-align: center;
            margin-bottom: 20px;
            font-size: 24px;
            font-weight: bold;
        }
        
        .customer-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .note-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .note-table th, .note-table td {
            border: 1px solid #333;
            padding: 8px;
            text-align: center;
        }
        
        .note-table th {
            background-color: #f2f2f2;
        }
        
        .footer {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
        }
        
        .history-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-top: 10px;
        }
        
        .history-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        
        .history-item:hover {
            background-color: #f9f9f9;
        }
        
        .history-detail {
            display: none;
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        
        .history-detail table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .history-detail th, .history-detail td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .history-detail th {
            background-color: #e9ecef;
        }
        
        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .export-btn {
            margin-left: 10px;
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .user-table th, .user-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .user-table th {
            background-color: #f2f2f2;
        }
        
        @media (max-width: 768px) {
            .customer-info {
                grid-template-columns: 1fr;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
            }
            
            .header {
                flex-direction: column;
                gap: 10px;
            }
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .delivery-note, .delivery-note * {
                visibility: visible;
            }
            .delivery-note {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <!-- 登录界面 -->
    <div class="login-container" id="loginContainer">
        <h1>送货单管理系统</h1>
        <form class="login-form" id="loginForm">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" placeholder="请输入用户名" required>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" placeholder="请输入密码" required>
            </div>
            <button type="submit" class="login-btn">登录</button>
        </form>
    </div>

    <!-- 主界面 -->
    <div class="container" id="mainContainer">
        <div class="header">
            <h1>送货单管理系统</h1>
            <div class="user-info">
                <span id="currentUser">用户</span>
                <button class="btn btn-danger" id="logoutBtn">退出登录</button>
            </div>
        </div>
        
        <div class="form-section">
            <h2>客户信息</h2>
            <div class="form-group">
                <label for="customerName">客户名称</label>
                <input type="text" id="customerName" placeholder="请输入客户名称">
            </div>
            <div class="form-group">
                <label for="customerPhone">联系电话</label>
                <input type="text" id="customerPhone" placeholder="请输入联系电话">
            </div>
            <div class="form-group">
                <label for="customerAddress">送货地址</label>
                <input type="text" id="customerAddress" placeholder="请输入送货地址">
            </div>
            <div class="form-group">
                <label for="deliveryDate">送货日期</label>
                <input type="date" id="deliveryDate">
            </div>
            
            <h2>产品信息</h2>
            <table class="product-table" id="productTable">
                <thead>
                    <tr>
                        <th width="5%">序号</th>
                        <th width="20%">产品名称</th>
                        <th width="15%">产品编码</th>
                        <th width="15%">型号规格</th>
                        <th width="10%">单位</th>
                        <th width="10%">数量</th>
                        <th width="15%">备注</th>
                        <th width="10%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>1</td>
                        <td><input type="text" class="product-name" placeholder="产品名称"></td>
                        <td><input type="text" class="product-code" placeholder="产品编码"></td>
                        <td><input type="text" class="product-spec" placeholder="型号规格"></td>
                        <td><input type="text" class="product-unit" placeholder="单位"></td>
                        <td><input type="number" class="product-quantity" placeholder="数量"></td>
                        <td><input type="text" class="product-remark" placeholder="备注"></td>
                        <td><button class="btn btn-danger remove-row">删除</button></td>
                    </tr>
                </tbody>
            </table>
            
            <button class="btn btn-primary" id="addProduct">添加产品</button>
            
            <div class="button-group">
                <button class="btn btn-success" id="generateNote">生成送货单</button>
                <button class="btn btn-primary" id="saveNote">保存送货单</button>
                <button class="btn btn-info" id="printNote">打印送货单</button>
                <button class="btn" id="clearForm">清空表单</button>
            </div>
        </div>
        
        <div class="preview-section">
            <h2>送货单预览</h2>
            <div class="preview-container">
                <div class="delivery-note" id="deliveryNotePreview">
                    <!-- 送货单预览将在这里显示 -->
                </div>
            </div>
        </div>
        
        <div class="history-section">
            <div class="history-header">
                <h2>历史记录</h2>
                <div>
                    <button class="btn btn-warning export-btn" id="exportHistory">导出历史记录</button>
                    <button class="btn btn-primary export-btn" id="printHistory">打印历史记录</button>
                </div>
            </div>
            <div class="history-list" id="historyList">
                <!-- 历史记录将在这里显示 -->
            </div>
        </div>
        
        <!-- 用户管理部分（仅超级管理员可见） -->
        <div class="user-management-section" id="userManagementSection" style="display: none;">
            <h2>用户管理</h2>
            <div class="form-group">
                <label for="newUsername">用户名</label>
                <input type="text" id="newUsername" placeholder="请输入新用户名">
            </div>
            <div class="form-group">
                <label for="newPassword">密码</label>
                <input type="password" id="newPassword" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label for="userRole">角色</label>
                <select id="userRole">
                    <option value="user">普通用户</option>
                    <option value="admin">管理员</option>
                </select>
            </div>
            <button class="btn btn-success" id="addUser">添加用户</button>
            
            <h3 style="margin-top: 20px;">用户列表</h3>
            <table class="user-table" id="userTable">
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 用户列表将在这里显示 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化用户数据
            if (!localStorage.getItem('users')) {
                const defaultUsers = [
                    { username: 'admin', password: 'admin123', role: 'admin' },
                    { username: 'user', password: 'user123', role: 'user' }
                ];
                localStorage.setItem('users', JSON.stringify(defaultUsers));
            }
            
            // 设置默认日期为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('deliveryDate').value = today;
            
            // 登录功能
            document.getElementById('loginForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;
                
                const users = JSON.parse(localStorage.getItem('users'));
                const user = users.find(u => u.username === username && u.password === password);
                
                if (user) {
                    // 保存当前用户信息
                    localStorage.setItem('currentUser', JSON.stringify(user));
                    
                    // 显示主界面，隐藏登录界面
                    document.getElementById('loginContainer').style.display = 'none';
                    document.getElementById('mainContainer').style.display = 'block';
                    
                    // 更新当前用户显示
                    document.getElementById('currentUser').textContent = `${user.username} (${user.role === 'admin' ? '管理员' : '普通用户'})`;
                    
                    // 如果是管理员，显示用户管理部分
                    if (user.role === 'admin') {
                        document.getElementById('userManagementSection').style.display = 'block';
                        loadUserList();
                    }
                    
                    // 初始化历史记录
                    loadHistory();
                    
                    // 初始生成一个空的送货单预览
                    generateDeliveryNote();
                } else {
                    alert('用户名或密码错误！');
                }
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                localStorage.removeItem('currentUser');
                document.getElementById('loginContainer').style.display = 'block';
                document.getElementById('mainContainer').style.display = 'none';
                document.getElementById('loginForm').reset();
            });
            
            // 检查是否已登录
            const currentUser = localStorage.getItem('currentUser');
            if (currentUser) {
                const user = JSON.parse(currentUser);
                document.getElementById('loginContainer').style.display = 'none';
                document.getElementById('mainContainer').style.display = 'block';
                document.getElementById('currentUser').textContent = `${user.username} (${user.role === 'admin' ? '管理员' : '普通用户'})`;
                
                // 如果是管理员，显示用户管理部分
                if (user.role === 'admin') {
                    document.getElementById('userManagementSection').style.display = 'block';
                    loadUserList();
                }
            }
            
            // 添加产品行
            document.getElementById('addProduct').addEventListener('click', function() {
                const table = document.getElementById('productTable');
                const tbody = table.querySelector('tbody');
                const rowCount = tbody.rows.length;
                
                const newRow = document.createElement('tr');
                newRow.innerHTML = `
                    <td>${rowCount + 1}</td>
                    <td><input type="text" class="product-name" placeholder="产品名称"></td>
                    <td><input type="text" class="product-code" placeholder="产品编码"></td>
                    <td><input type="text" class="product-spec" placeholder="型号规格"></td>
                    <td><input type="text" class="product-unit" placeholder="单位"></td>
                    <td><input type="number" class="product-quantity" placeholder="数量"></td>
                    <td><input type="text" class="product-remark" placeholder="备注"></td>
                    <td><button class="btn btn-danger remove-row">删除</button></td>
                `;
                
                tbody.appendChild(newRow);
                
                // 添加删除行的事件监听
                newRow.querySelector('.remove-row').addEventListener('click', function() {
                    tbody.removeChild(newRow);
                    updateRowNumbers();
                });
            });
            
            // 删除产品行
            document.addEventListener('click', function(e) {
                if (e.target && e.target.classList.contains('remove-row')) {
                    const row = e.target.closest('tr');
                    const tbody = document.getElementById('productTable').querySelector('tbody');
                    tbody.removeChild(row);
                    updateRowNumbers();
                }
            });
            
            // 更新行号
            function updateRowNumbers() {
                const rows = document.querySelectorAll('#productTable tbody tr');
                rows.forEach((row, index) => {
                    row.cells[0].textContent = index + 1;
                });
            }
            
            // 生成送货单预览
            document.getElementById('generateNote').addEventListener('click', function() {
                generateDeliveryNote();
            });
            
            // 生成送货单
            function generateDeliveryNote() {
                const customerName = document.getElementById('customerName').value || '客户名称';
                const customerPhone = document.getElementById('customerPhone').value || '联系电话';
                const customerAddress = document.getElementById('customerAddress').value || '送货地址';
                const deliveryDate = document.getElementById('deliveryDate').value || '送货日期';
                
                // 获取产品数据
                const productRows = document.querySelectorAll('#productTable tbody tr');
                let productHTML = '';
                let totalAmount = 0;
                
                productRows.forEach(row => {
                    const name = row.querySelector('.product-name').value || '';
                    const code = row.querySelector('.product-code').value || '';
                    const spec = row.querySelector('.product-spec').value || '';
                    const unit = row.querySelector('.product-unit').value || '';
                    const quantity = row.querySelector('.product-quantity').value || '';
                    const remark = row.querySelector('.product-remark').value || '';
                    
                    productHTML += `
                        <tr>
                            <td>${row.cells[0].textContent}</td>
                            <td>${name}</td>
                            <td>${spec}</td>
                            <td>${unit}</td>
                            <td>${quantity}</td>
                            <td>${remark}</td>
                        </tr>
                    `;
                    
                    // 计算小计（这里简单处理，实际可能需要根据单价计算）
                    totalAmount += parseInt(quantity) || 0;
                });
                
                // 格式化日期
                const formattedDate = formatDate(deliveryDate);
                
                // 生成送货单编号
                const noteNumber = generateNoteNumber();
                
                // 构建送货单HTML
                const deliveryNoteHTML = `
                    <div class="company-header">漫花纸业</div>
                    
                    <div class="customer-info">
                        <div>客户名称：${customerName}</div>
                        <div>客户地址：${customerAddress}</div>
                        <div>联系电话：${customerPhone}</div>
                        <div>送货日期：${formattedDate}</div>
                    </div>
                    
                    <table class="note-table">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>产品名称</th>
                                <th>型号规格</th>
                                <th>单位</th>
                                <th>数量</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${productHTML}
                        </tbody>
                    </table>
                    
                    <div>小计：${totalAmount.toLocaleString()}</div>
                    
                    <hr>
                    
                    <div class="footer">
                        <div>
                            <div>送货单</div>
                            <div>NO. ${noteNumber}</div>
                        </div>
                        <div>页码：1/1页</div>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        注：以上货品请在收货时点清，如有差错请在三个工作日内联系。逾期恕不负责。
                    </div>
                    
                    <div style="margin-top: 30px; display: flex; justify-content: space-between;">
                        <div>送货单位经手人：</div>
                        <div>收货单位及经手人（签章）：</div>
                    </div>
                `;
                
                document.getElementById('deliveryNotePreview').innerHTML = deliveryNoteHTML;
            }
            
            // 打印送货单
            document.getElementById('printNote').addEventListener('click', function() {
                const deliveryNote = document.getElementById('deliveryNotePreview');
                if (deliveryNote.innerHTML.trim() === '') {
                    alert('请先生成送货单！');
                    return;
                }
                
                // 创建一个新的窗口用于打印
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                    <head>
                        <title>打印送货单</title>
                        <style>
                            body { font-family: "Microsoft YaHei", sans-serif; margin: 20px; }
                            .company-header { text-align: center; margin-bottom: 20px; font-size: 24px; font-weight: bold; }
                            .customer-info { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
                            .note-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
                            .note-table th, .note-table td { border: 1px solid #333; padding: 8px; text-align: center; }
                            .note-table th { background-color: #f2f2f2; }
                            .footer { margin-top: 20px; display: flex; justify-content: space-between; }
                        </style>
                    </head>
                    <body>
                        ${deliveryNote.innerHTML}
                    </body>
                    </html>
                `);
                printWindow.document.close();
                printWindow.print();
            });
            
            // 格式化日期
            function formatDate(dateString) {
                const date = new Date(dateString);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            }
            
            // 生成送货单编号
            function generateNoteNumber() {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
                return `${year}${month}${day}${random}`;
            }
            
            // 保存送货单
            document.getElementById('saveNote').addEventListener('click', function() {
                const customerName = document.getElementById('customerName').value;
                const customerPhone = document.getElementById('customerPhone').value;
                const customerAddress = document.getElementById('customerAddress').value;
                const deliveryDate = document.getElementById('deliveryDate').value;
                
                if (!customerName || !customerPhone || !customerAddress || !deliveryDate) {
                    alert('请填写完整的客户信息');
                    return;
                }
                
                // 获取产品数据
                const productRows = document.querySelectorAll('#productTable tbody tr');
                const products = [];
                
                productRows.forEach(row => {
                    const name = row.querySelector('.product-name').value;
                    const code = row.querySelector('.product-code').value;
                    const spec = row.querySelector('.product-spec').value;
                    const unit = row.querySelector('.product-unit').value;
                    const quantity = row.querySelector('.product-quantity').value;
                    const remark = row.querySelector('.product-remark').value;
                    
                    if (name) {
                        products.push({
                            name,
                            code,
                            spec,
                            unit,
                            quantity,
                            remark
                        });
                    }
                });
                
                if (products.length === 0) {
                    alert('请至少添加一个产品');
                    return;
                }
                
                // 创建送货单对象
                const deliveryNote = {
                    id: Date.now(),
                    customerName,
                    customerPhone,
                    customerAddress,
                    deliveryDate,
                    products,
                    noteNumber: generateNoteNumber(),
                    createdAt: new Date().toISOString()
                };
                
                // 保存到本地存储
                saveDeliveryNote(deliveryNote);
                
                // 更新历史记录
                loadHistory();
                
                alert('送货单保存成功！');
            });
            
            // 保存送货单到本地存储
            function saveDeliveryNote(deliveryNote) {
                let notes = JSON.parse(localStorage.getItem('deliveryNotes')) || [];
                notes.push(deliveryNote);
                localStorage.setItem('deliveryNotes', JSON.stringify(notes));
            }
            
            // 加载历史记录
            function loadHistory() {
                const historyList = document.getElementById('historyList');
                const notes = JSON.parse(localStorage.getItem('deliveryNotes')) || [];
                
                historyList.innerHTML = '';
                
                if (notes.length === 0) {
                    historyList.innerHTML = '<div style="text-align: center; color: #777;">暂无历史记录</div>';
                    return;
                }
                
                // 按创建时间倒序排列
                notes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
                
                notes.forEach(note => {
                    const historyItem = document.createElement('div');
                    historyItem.className = 'history-item';
                    historyItem.innerHTML = `
                        <div><strong>${note.customerName}</strong> - ${formatDate(note.deliveryDate)}</div>
                        <div>${note.noteNumber} - ${note.products.length}个产品</div>
                        <div class="history-detail">
                            <div><strong>客户信息</strong></div>
                            <div>客户名称: ${note.customerName}</div>
                            <div>联系电话: ${note.customerPhone}</div>
                            <div>送货地址: ${note.customerAddress}</div>
                            <div>送货日期: ${formatDate(note.deliveryDate)}</div>
                            <div><strong>产品明细</strong></div>
                            <table>
                                <thead>
                                    <tr>
                                        <th>产品名称</th>
                                        <th>产品编码</th>
                                        <th>型号规格</th>
                                        <th>单位</th>
                                        <th>数量</th>
                                        <th>备注</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${note.products.map(product => `
                                        <tr>
                                            <td>${product.name}</td>
                                            <td>${product.code || ''}</td>
                                            <td>${product.spec || ''}</td>
                                            <td>${product.unit || ''}</td>
                                            <td>${product.quantity || ''}</td>
                                            <td>${product.remark || ''}</td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                            <div style="margin-top: 10px;">
                                <button class="btn btn-primary export-btn export-single" data-id="${note.id}">导出此送货单</button>
                            </div>
                        </div>
                    `;
                    
                    historyItem.addEventListener('click', function(e) {
                        // 如果点击的是导出按钮，则不切换详情显示
                        if (e.target.classList.contains('export-single')) {
                            exportSingleNote(note);
                            return;
                        }
                        
                        // 切换详情显示
                        const detail = this.querySelector('.history-detail');
                        const allDetails = document.querySelectorAll('.history-detail');
                        
                        allDetails.forEach(d => {
                            if (d !== detail) d.style.display = 'none';
                        });
                        
                        detail.style.display = detail.style.display === 'block' ? 'none' : 'block';
                    });
                    
                    historyList.appendChild(historyItem);
                });
            }
            
            // 导出单个送货单
            function exportSingleNote(note) {
                let csvContent = "客户名称,联系电话,送货地址,送货日期,送货单号\n";
                csvContent += `"${note.customerName}","${note.customerPhone}","${note.customerAddress}","${formatDate(note.deliveryDate)}","${note.noteNumber}"\n\n`;
                
                csvContent += "产品名称,产品编码,型号规格,单位,数量,备注\n";
                note.products.forEach(product => {
                    csvContent += `"${product.name}","${product.code || ''}","${product.spec || ''}","${product.unit || ''}","${product.quantity || ''}","${product.remark || ''}"\n`;
                });
                
                downloadCSV(csvContent, `送货单_${note.noteNumber}_${formatDate(note.deliveryDate)}.csv`);
            }
            
            // 导出历史记录
            document.getElementById('exportHistory').addEventListener('click', function() {
                const notes = JSON.parse(localStorage.getItem('deliveryNotes')) || [];
                
                if (notes.length === 0) {
                    alert('没有历史记录可导出');
                    return;
                }
                
                let csvContent = "序号,客户名称,联系电话,送货地址,送货日期,送货单号,产品数量\n";
                
                notes.forEach((note, index) => {
                    csvContent += `${index + 1},"${note.customerName}","${note.customerPhone}","${note.customerAddress}","${formatDate(note.deliveryDate)}","${note.noteNumber}",${note.products.length}\n`;
                });
                
                downloadCSV(csvContent, `送货单历史记录_${formatDate(new Date())}.csv`);
            });
            
            // 打印历史记录
            document.getElementById('printHistory').addEventListener('click', function() {
                const notes = JSON.parse(localStorage.getItem('deliveryNotes')) || [];
                
                if (notes.length === 0) {
                    alert('没有历史记录可打印');
                    return;
                }
                
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                    <head>
                        <title>送货单历史记录</title>
                        <style>
                            body { font-family: Arial, sans-serif; margin: 20px; }
                            table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                            th { background-color: #f2f2f2; }
                            h1 { text-align: center; }
                        </style>
                    </head>
                    <body>
                        <h1>送货单历史记录</h1>
                        <table>
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>客户名称</th>
                                    <th>联系电话</th>
                                    <th>送货地址</th>
                                    <th>送货日期</th>
                                    <th>送货单号</th>
                                    <th>产品数量</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${notes.map((note, index) => `
                                    <tr>
                                        <td>${index + 1}</td>
                                        <td>${note.customerName}</td>
                                        <td>${note.customerPhone}</td>
                                        <td>${note.customerAddress}</td>
                                        <td>${formatDate(note.deliveryDate)}</td>
                                        <td>${note.noteNumber}</td>
                                        <td>${note.products.length}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </body>
                    </html>
                `);
                printWindow.document.close();
                printWindow.print();
            });
            
            // 下载CSV文件
            function downloadCSV(csvContent, filename) {
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                
                if (link.download !== undefined) {
                    const url = URL.createObjectURL(blob);
                    link.setAttribute('href', url);
                    link.setAttribute('download', filename);
                    link.style.visibility = 'hidden';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            }
            
            // 添加用户
            document.getElementById('addUser').addEventListener('click', function() {
                const username = document.getElementById('newUsername').value;
                const password = document.getElementById('newPassword').value;
                const role = document.getElementById('userRole').value;
                
                if (!username || !password) {
                    alert('请输入用户名和密码');
                    return;
                }
                
                const users = JSON.parse(localStorage.getItem('users'));
                
                // 检查用户名是否已存在
                if (users.find(u => u.username === username)) {
                    alert('用户名已存在');
                    return;
                }
                
                // 添加新用户
                users.push({ username, password, role });
                localStorage.setItem('users', JSON.stringify(users));
                
                // 更新用户列表
                loadUserList();
                
                // 清空表单
                document.getElementById('newUsername').value = '';
                document.getElementById('newPassword').value = '';
                
                alert('用户添加成功！');
            });
            
            // 加载用户列表
            function loadUserList() {
                const users = JSON.parse(localStorage.getItem('users'));
                const userTable = document.getElementById('userTable').querySelector('tbody');
                
                userTable.innerHTML = '';
                
                users.forEach(user => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${user.username}</td>
                        <td>${user.role === 'admin' ? '管理员' : '普通用户'}</td>
                        <td>
                            <button class="btn btn-danger delete-user" data-username="${user.username}">删除</button>
                        </td>
                    `;
                    userTable.appendChild(row);
                });
                
                // 添加删除用户的事件监听
                document.querySelectorAll('.delete-user').forEach(button => {
                    button.addEventListener('click', function() {
                        const username = this.getAttribute('data-username');
                        deleteUser(username);
                    });
                });
            }
            
            // 删除用户
            function deleteUser(username) {
                // 不能删除当前登录用户
                const currentUser = JSON.parse(localStorage.getItem('currentUser'));
                if (currentUser.username === username) {
                    alert('不能删除当前登录用户！');
                    return;
                }
                
                // 不能删除最后一个管理员
                const users = JSON.parse(localStorage.getItem('users'));
                const adminUsers = users.filter(u => u.role === 'admin');
                if (adminUsers.length === 1 && adminUsers[0].username === username) {
                    alert('不能删除最后一个管理员！');
                    return;
                }
                
                if (confirm(`确定要删除用户 "${username}" 吗？`)) {
                    const updatedUsers = users.filter(u => u.username !== username);
                    localStorage.setItem('users', JSON.stringify(updatedUsers));
                    loadUserList();
                    alert('用户删除成功！');
                }
            }
            
            // 将历史记录加载到表单
            function loadNoteToForm(note) {
                document.getElementById('customerName').value = note.customerName;
                document.getElementById('customerPhone').value = note.customerPhone;
                document.getElementById('customerAddress').value = note.customerAddress;
                document.getElementById('deliveryDate').value = note.deliveryDate;
                
                // 清空现有产品行
                const tbody = document.getElementById('productTable').querySelector('tbody');
                tbody.innerHTML = '';
                
                // 添加产品行
                note.products.forEach((product, index) => {
                    const newRow = document.createElement('tr');
                    newRow.innerHTML = `
                        <td>${index + 1}</td>
                        <td><input type="text" class="product-name" value="${product.name}"></td>
                        <td><input type="text" class="product-code" value="${product.code || ''}"></td>
                        <td><input type="text" class="product-spec" value="${product.spec || ''}"></td>
                        <td><input type="text" class="product-unit" value="${product.unit || ''}"></td>
                        <td><input type="number" class="product-quantity" value="${product.quantity || ''}"></td>
                        <td><input type="text" class="product-remark" value="${product.remark || ''}"></td>
                        <td><button class="btn btn-danger remove-row">删除</button></td>
                    `;
                    
                    tbody.appendChild(newRow);
                    
                    // 添加删除行的事件监听
                    newRow.querySelector('.remove-row').addEventListener('click', function() {
                        tbody.removeChild(newRow);
                        updateRowNumbers();
                    });
                });
                
                // 生成预览
                generateDeliveryNote();
            }
            
            // 清空表单
            document.getElementById('clearForm').addEventListener('click', function() {
                document.getElementById('customerName').value = '';
                document.getElementById('customerPhone').value = '';
                document.getElementById('customerAddress').value = '';
                document.getElementById('deliveryDate').value = today;
                
                // 清空产品表，只保留一行
                const tbody = document.getElementById('productTable').querySelector('tbody');
                tbody.innerHTML = `
                    <tr>
                        <td>1</td>
                        <td><input type="text" class="product-name" placeholder="产品名称"></td>
                        <td><input type="text" class="product-code" placeholder="产品编码"></td>
                        <td><input type="text" class="product-spec" placeholder="型号规格"></td>
                        <td><input type="text" class="product-unit" placeholder="单位"></td>
                        <td><input type="number" class="product-quantity" placeholder="数量"></td>
                        <td><input type="text" class="product-remark" placeholder="备注"></td>
                        <td><button class="btn btn-danger remove-row">删除</button></td>
                    </tr>
                `;
                
                // 清空预览
                document.getElementById('deliveryNotePreview').innerHTML = '';
                
                // 添加删除行的事件监听
                document.querySelector('.remove-row').addEventListener('click', function() {
                    // 如果只剩一行，不清除，只是清空内容
                    const rows = document.querySelectorAll('#productTable tbody tr');
                    if (rows.length > 1) {
                        const row = this.closest('tr');
                        tbody.removeChild(row);
                        updateRowNumbers();
                    } else {
                        // 清空这一行的内容
                        const inputs = rows[0].querySelectorAll('input');
                        inputs.forEach(input => input.value = '');
                    }
                });
            });
        });
    </script>
</body>
</html>